from loguru import logger
from flask import request
import sys
import os

def setup_logger(app):
    """设置日志配置"""
    # 创建日志目录
    log_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'logs')
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    
    # 设置日志文件路径
    log_file = os.path.join(log_dir, 'app.log')
    
    # 配置日志格式和输出
    logger.remove()  # 移除默认的处理器
    logger.add(
        sys.stdout,
        format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <yellow>{message}</yellow>",
        level="DEBUG",
        backtrace=True,
        diagnose=True
    )
    logger.add(
        log_file,
        format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
        rotation="500 MB",
        retention="10 days",
        level="DEBUG"
    )
    
    # 添加请求日志记录
    @app.before_request
    def before_request():
        logger.info(f"访问路径: {request.method} {request.path}")
        if request.args:
            logger.debug(f"查询参数: {dict(request.args)}")
        if request.is_json:
            logger.debug(f"请求数据: {request.get_json()}")
        elif request.form:
            logger.debug(f"表单数据: {dict(request.form)}")
    
    @app.after_request
    def after_request(response):
        logger.info(f"Response: {response.status}")
        return response
    
    return logger